package com.fafu.control;

import com.fafu.dao.mapper.StudentMapper;
import com.fafu.model.Studentrepair;;
import com.fafu.pojo.AppPojo4list;
import com.fafu.pojo.MessageAndPics;
import com.fafu.pojo.StudentRepairInputPojo;
import com.fafu.service.AppService;
import com.fafu.service.OtherService;
import com.fafu.service.StudentRepairService;
import com.fafu.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import util.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.RequestWrapper;
import java.sql.Time;
import java.util.List;
import java.util.Map;

import static util.Dictionary.CODE.IS_DECLARE_REPAIR;
import static util.Dictionary.CODE.SUCCESS;
import static util.Dictionary.REPAIR.PREPARE_REPAIR_IS_DECLARE;
import static util.Dictionary.REPAIR.PREPARE_REPAIR_SUCCESS;

/**
 * 登陆接口使用user中的
 * 报修使用 repairColtrol中的
 */
@Api("用于学生android端接口")
@RestController()
@RequestMapping(value = "/app")
public class AppControl {
    private Logger logger = LoggerFactory.getLogger(AppControl.class);
    @Autowired
    private AppService appService;
    @Autowired
    private StudentRepairService studentRepairService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private StudentService studentService;
    @Autowired
    private OtherService otherService;
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public JsonRsp search(
            @RequestParam(value = "id") @ApiParam("学生id") Integer id,
            @RequestParam(value = "type") @ApiParam("查询类别:0历史，1未读，2未处理, 3进行中，4拒绝") String type) {
        try {
            Map<String,Object> map = appService.selectRecordList(new MyMap().put("id",id).put("type",type).toMap());
            List<AppPojo4list> appPojo4listList = (List<AppPojo4list>) map.get("data");
            for(AppPojo4list data:appPojo4listList){
//                data.setAddTimeStr(TimeChange.Long2Date(data.getAddTime()));
//                System.out.println(data.getState());
                data.setStateStr(StateChange.getStateStr(data.getState()));

            }
            return  JsonRsp.success(map.get("data"));
        } catch (Exception e) {
            logger.error("system error" + e);
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR, "system error");
        }
    }

    @RequestMapping(value = "/searchItem",method = RequestMethod.GET)
    public JsonRsp searchItem(
            @RequestParam(value = "recordid") @ApiParam("记录id") Integer recordId){
        try {
            /**
             * 查询用户，存入redis,返回token
             */
            Map map = appService.selectRecordItem(new MyMap().put("id",recordId).toMap());
            return  JsonRsp.success(map.get("data"));
        } catch (Exception e) {
            logger.error("system error" + e);
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR, "system error");
        }
    }
    @RequestMapping(value = "/changeRecord",method = RequestMethod.POST)
    public JsonRsp changeRecor(
            @RequestParam(value = "id") @ApiParam Integer id
            ,@RequestParam(value="msg") @ApiParam String msg){
        try {
            Map map = appService.updateRecordItem(new MyMap().put("id",id).put("msg",msg).toMap());
            Integer code = (Integer) map.get("code");
            if(code == 200)
                return  JsonRsp.success("success");
            return JsonRsp.fail(code, (String) map.get("msg"));
        } catch (Exception e) {
            logger.error("system error" + e);
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR, "system error");
        }
    }

    @ApiOperation("学生报修")
    @RequestMapping(value = "/studentRepair", method=RequestMethod.POST)
    public JsonRsp studentRepair(
            @RequestBody @ApiParam("学生报修信息") StudentRepairInputPojo studentRepairInputPojo
            ,@RequestParam(value = "isAlert", defaultValue = "1") @ApiParam(value = "是否广播")Integer isAlert){
//            @RequestParam(value = "type")@ApiParam("维修类别") Integer type
//            , @RequestBody @Validated Studentrepair studentrepair
//            , BindingResult result
//            , @RequestBody(required = false) ArrayList<Integer>picIdList){

        try{
            logger.info(studentRepairInputPojo.toString());
            Studentrepair studentrepair = new Studentrepair();
            Integer type = studentRepairInputPojo.getType();
            BeanUtils.copyProperties(studentRepairInputPojo,studentrepair);
            List<Integer> picIdList = studentRepairInputPojo.getPicIdList();
            int a= 1;
            Map<String,Object> insertResult = studentRepairService.studentRepair(studentrepair,picIdList);
            Integer code = (Integer) insertResult.get("code");

            if(code.equals( PREPARE_REPAIR_IS_DECLARE)){
                return JsonRsp.fail(IS_DECLARE_REPAIR,"有未处理报修",insertResult.get("data"));
            }
            if(code.equals(PREPARE_REPAIR_SUCCESS)){
                //广播回去，让前端再查
                if(isAlert == 1)
                    messagingTemplate.convertAndSend("/demo_2/topic/getResponse","search");
                return JsonRsp.success(new MyMap().put("id",insertResult.get("data")).toMap(),"success");
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
        return null;//永远进不来
    }
    @ApiOperation("获得学生地址")
    @RequestMapping(value = "/getAddr", method=RequestMethod.GET)
    public JsonRsp getAddr(@RequestParam(value = "studentId") String studentId){
        try{
            String studentAddr = appService.selectAddr(studentId);
            if(studentAddr.equals("-1"))
                return JsonRsp.fail(100,"iden error");
            return JsonRsp.success(studentAddr);
        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }

    }
    @ApiOperation("学生登录")
    @RequestMapping(value = "/stulogin", method=RequestMethod.GET)
    public JsonRsp stulogin(
            @RequestParam(value = "studentId") String studentId
            ,@RequestParam(value = "password") String password){
        try{
            Map<String,Object> map = studentService.login(new MyMap().put("studentId",studentId).put("password",password).toMap());
            if(map.get("code").equals(SUCCESS))
                return JsonRsp.success(new MyMap()
                        .put("iden",map.get("studentIden"))
                        .put("id",map.get("id"))
                        .put("isused",map.get("isused"))
                        .put("imgurl",map.get("imgurl"))
                        .put("name",map.get("name"))
                        .put("area",map.get("area")).toMap());
            else
                return JsonRsp.fail((Integer)map.get("code"),(String) map.get("msg"));
        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
    }
    @ApiOperation("密码修改")
    @RequestMapping(value = "/pwdchange", method=RequestMethod.GET)
    public JsonRsp pwdchange(
            @RequestParam(value = "studentId") String studentId
            , @RequestParam(value = "oldpwd") String oldpwd
            , @RequestParam(value = "newpwd") String newpwd){
        try{
            Map<String,Object> map = studentService.changePwd(new MyMap().put("studentId",studentId).put("oldpwd",oldpwd).put("newpwd",newpwd).toMap());
            if(map.get("code").equals(SUCCESS))
                return JsonRsp.success(new MyMap().put("msg","success").toMap());
            else
                return JsonRsp.fail((Integer)map.get("code"),(String) map.get("msg"));
        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
    }
    @ApiOperation("修改信息")
    @RequestMapping(value = "/msgChange", method=RequestMethod.GET)
    public JsonRsp msgChange(
            @RequestParam(value = "reid") Integer reid
            ,@RequestParam(value = "msg") String msg){
        try{
            Map<String,Object> map = studentService.msgChange(new MyMap().put("reid",reid).put("msg",msg).toMap());
            if(map.get("code").equals(SUCCESS))
                return JsonRsp.success(new MyMap().put("msg","success").toMap());
            else
                return JsonRsp.fail((Integer)map.get("code"),(String) map.get("msg"));
        }catch (Exception e){
            logger.error(e.getMessage());
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }
    }

    @ApiOperation("新增公共报修")
    @RequestMapping(value = "/repair",method = RequestMethod.POST)
    public JsonRsp studentRepair(
            @RequestBody @ApiParam("报修的信息") MessageAndPics message
            ,@RequestParam(value = "isAlert", defaultValue = "1") @ApiParam(value = "是否广播")Integer isAlert){
        try{
            message.setState(Dictionary.REPAIR.REPAIR_STATE_NO_READ);
            message.setAddTime(System.currentTimeMillis());
            int a = 0;
            Map<String,Object> remap = otherService.addMessage(new MyMap().put("data",message).toMap());
            if(isAlert == 1)
                messagingTemplate.convertAndSend("/demo_2/topic/getResponse","search");
            return JsonRsp.success(new MyMap().put("id",remap.get("data")).toMap());
        }catch (Exception e){
            logger.error("系统内部错误"+e);
            return JsonRsp.fail(Dictionary.CODE.SYSTEM_ERROR,"系统内部错误");
        }

    }
}
